/**
 * 使用简单网络请求
 */
// 1.dart io发起的请求
// get 
import 'dart:io';//导IO包
import 'dart:convert';//解码和编码JSON
void main1() {
  _get();
}

_get() async{
  var responseBody;
  //1.创建HttpClient
  var httpClient = new HttpClient();
  //2.构造Uri
  var requset = await httpClient.getUrl(Uri.parse("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1"));
  //3.关闭请求，等待响应
  var response = await requset.close();
  //4.进行解码，获取数据
  if(response.statusCode == 200){
      //拿到请求的数据
      responseBody = await response.transform(utf8.decoder).join();
      //先不解析打印数据
      print(responseBody);
  }else{
    print("error");
  }
  
}
_post() async{
  var responseBody;
  //1.创建HttpClient
  var httpClient = new HttpClient();
  //2.构造Uri
  var requset = await httpClient.postUrl(Uri.parse("http://www.wanandroid.com/user/login?username=1&password=123456"));
  //3.关闭请求，等待响应
  var response = await requset.close();
  //4.进行解码，获取数据
  if(response.statusCode == 200){
  //拿到请求的数据
  responseBody = await response.transform(utf8.decoder).join();
  //先不解析打印数据
    print(responseBody);
  }else{
    print("error");
  }

}

/**
 * dio请求
 * dio是一个强大的Dart Http请求库，支持Restful API、FormData、拦截器、错误处理、转换器、设置Http代理、请求取消、Cookie管理、文件上传和下载、超时等
 * 1.在pubspec.yaml添加依赖 dio: ^2.0.14
 * 2.导入依赖 import 'package:dio/dio.dart';
 */
//dio get请求
dio_get() async{
  try{
      Response response;
      //等待返回response
      response = await Dio().get("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1");
      if(response.statusCode == 200){
        print(response);
      }else{
        print("error");
      }
  }catch(e){
     print(e);

  }
}
// post请求
dio_post() async{
  try{
    Response response;
    response = await Dio().post("http://www.wanandroid.com/user/login?username=1&password=123456");
    if(response.statusCode == 200){
      print(response);
    }else{
      print("error");
    }
  }catch(e){
    print(e);
  }
}


/**
 * http库
 * 1.在pubspec.yaml添加依赖 http 0.12.0+1
 * 2.导入依赖 import 'package:http/http.dart' as my_http;
 */

//http库的get 请求方式
http_get() async{
  try{
    //因为导入http 用了as xxx方式，所以对象请求都用xxx.get方式
    var response = await my_http.get("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1");
    if(response.statusCode == 200){
      //打印返回的数据
      print(response.body);
    }else{
      print("error");
    }
  }catch(e){
    print(e);
  }
}

//http库的post请求方式
http_post() async{
  try{
    //因为导入http 用了as xxx方式，所以对象请求都用xxx.get方式
    var response = await my_http.post("http://www.wanandroid.com/user/login?username=1&password=123456");
    if(response.statusCode == 200){
      //打印返回的数据
      print(response.body);
    }else{
      print("error");
    }
  }catch(e){
    print(e);
  }
}




